package NIO;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * 通过allocate()获取缓冲区
 *
 * 参数：position <= limit <= capacity
 */

public class TestBuffer {

    @Test
    public void test1(){
        String str = "abcde";

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("---------allocate()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        buffer.put(str.getBytes());
        System.out.println("---------put()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        buffer.flip(); // 切换到读模式
        System.out.println("---------flip()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst);
        System.out.println(new String(dst, 0, dst.length));

        System.out.println("---------get()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        buffer.rewind(); // 可重复读数据
        System.out.println("---------rewind()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        buffer.clear();
        System.out.println("---------clear()----------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
    }

    @Test
    public void test2(){ // 测试mark属性
        String str = "abcde";
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        buffer.flip();

        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst, 0, 2);
        System.out.println(new String(dst, 0, 2));
        System.out.println(buffer.position());

        buffer.mark();
        buffer.get(dst, 2, 2);
        System.out.println(new String(dst, 2, 2));
        System.out.println(buffer.position());

        buffer.reset(); // 恢复到mark的位置
        System.out.println(buffer.position());
    }

    @Test
    public void test3(){
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        System.out.println(buffer.isDirect());
    }

}
